import { useEffect, useRef } from "react";
import * as pdfjs from "pdfjs-dist";

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.mjs",
  import.meta.url
).toString();

const PDFPreview = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    loadPDF();
  }, []);

  const loadPDF = async () => {
    const loadingTask = pdfjs.getDocument(
      "https://zhuzian-111.oss-cn-beijing.aliyuncs.com/zhuzian.pdf"
    );
    const pdfDoc = await loadingTask.promise;
    const page = await pdfDoc.getPage(1);
    const viewport = page.getViewport({ scale: 1 });
    const canvas = canvasRef.current;
    if (canvas) {
      const context = canvas.getContext("2d");
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      if (context) {
        const renderContext = {
          canvasContext: context,
          viewport: viewport,
        };
        const renderTask = page.render(renderContext);
        await renderTask.promise;
      }
    }
  };
  return (
    <>
      <canvas ref={canvasRef} />
    </>
  );
};

export default PDFPreview;
